
module Spider where

import Data.Char
import System.Directory
import Monad
import System.FilePath

listDirs :: [FilePath] -> IO [FilePath]
listDirs = filterM doesDirectoryExist

listFiles :: [FilePath] -> IO [FilePath]
listFiles = filterM doesFileExist

joinFN :: String -> String -> FilePath
joinFN p1 p2 = joinPath [p1, p2]

isDotOrDoubleDot :: String -> Bool
isDotOrDoubleDot s =
    case s of
        "." -> True
        ".." -> True
        _ -> False

walk :: (String -> IO ()) -> String -> IO ()
walk f path = do
    ls <- getDirectoryContents path
    let ls_filtered = map (joinFN path) $ filter (not . isDotOrDoubleDot) ls
    files <- listFiles ls_filtered
    dirs <- listDirs ls_filtered
    
    mapM f files
    mapM (walk f) $ map (joinFN path) dirs
    return ()

listR :: String -> IO [FilePath]
listR path = do
    ls <- getDirectoryContents path
    let ls_filtered = map (joinFN path) $ filter (not . isDotOrDoubleDot) ls
    files <- listFiles ls_filtered
    dirs <- listDirs ls_filtered
    
    subdirs <- mapM listR $ map (joinFN path) dirs
    return $ files ++ foldl (++) [] subdirs

main = do
    cwd <- getCurrentDirectory
    files <- listR cwd
    putStrLn $ show files
--    walk putStrLn cwd
    
